<template>
    <view>
        <view class="uni-padding-wrap">
			<block v-if="hasRecord">
				<view class="page-body-time">
				    <text class="time-big">{{formatedPlayTime}}</text>
				    <text class="time-small">{{formatedRecordTime}}</text>
				</view>
				<view class="page-body-buttons">
				    <view class="page-body-button" @click="playVoice" v-if="!playing">
				        <image src="@/static/images/icon/play.png"></image>
				    </view>
					<view class="page-body-button" @click="stopVoice" v-if="playing">
					    <image src="@/static/images/icon/stop.png"></image>
					</view>
				    <view class="page-body-button" @click="clear">
				        <image src="@/static/images/icon/trash.png"></image>
				    </view>
				</view>
			</block>
			<block v-else>
				<view class="page-body-time">
				    <text class="time-big">{{formatedRecordTime}}</text>
				</view>
				<view class="page-body-buttons">
				    <view class="page-body-button" @click="startRecord" v-if="!recording">
				        <image src="@/static/images/icon/record.png"></image>
				    </view>
					<view class="page-body-button" @click="stopRecord" v-if="recording">
					    <view class="button-stop-record"></view>
					</view>
				</view>
			</block>
        </view>
		<view class="uploadBtn" v-if="hasRecord || playing">
			<button type="primary" @click="onUpload">上传录音</button>
		</view>
    </view>
</template>
<script>
	import permision from "@/utils/permission.js"
    import { utilities, file } from '@/utils/common.js'
	import * as sqliteUtil from '@/utils/sqlite.js'
	
    var playTimeInterval = null;
    var recordTimeInterval = null;
    var recorderManager = null;
    var music = null;
    export default {
        data() {
            return {
                recording: false, //录音中
                playing: false, //播放中
                hasRecord: false, //是否录音完成
                recordTime: 0,
                playTime: 0,
                formatedRecordTime: '00:00:00', //录音的总时间
                formatedPlayTime: '00:00:00' ,//播放录音的当前时间
				emitkey: 'RECORDING',
				source: null
            }
        },
        onUnload() {
            this.end();
        },
        onLoad(params) {
			if(params.emitkey) {
				this.emitkey = params.emitkey
			}
			if(params.source) {
				this.source = JSON.parse(params.source)
			}
			
            music = uni.createInnerAudioContext();
            music.onEnded(() => {
                clearInterval(playTimeInterval)
                var playTime = 0
                this.playing = false;
                this.formatedPlayTime = utilities.formatTime(playTime);
                this.playTime = playTime;
            });
            recorderManager = uni.getRecorderManager();
            recorderManager.onStart(() => {
                console.log('recorder start');

                this.recording = true;
                recordTimeInterval = setInterval(() => {
                    this.recordTime += 1;
                    this.formatedRecordTime = utilities.formatTime(this.recordTime);
                }, 1000)
            });
            recorderManager.onStop((res) => {
                console.log('recorder stop');
                music.src = res.tempFilePath;

                this.hasRecord = true;
                this.recording = false;
            });
            recorderManager.onError(() => {
                console.log('recorder error');
            });
        },
        methods: {
            async startRecord() { //开始录音
                // #ifdef APP-PLUS
                let status = await this.checkPermission();
                if (status !== 1) {
                    return;
                }
                // #endif

                recorderManager.start({
                    format: 'mp3',
					duration: 600000,
					sampleRate: 8000
                });
            },
            stopRecord() { //停止录音
                recorderManager.stop();
                clearInterval(recordTimeInterval);
            },
            playVoice() {
                this.playing = true;
                playTimeInterval = setInterval(() => {
                    this.playTime += 1;
                    this.formatedPlayTime = utilities.formatTime(this.playTime);
                }, 1000)
                music.play();
            },
            stopVoice() {
                clearInterval(playTimeInterval)
                this.playing = false;
                this.formatedPlayTime = utilities.formatTime(0);
                this.playTime = 0;
                music.stop();
            },
            end() {
                music.stop();
                recorderManager.stop();
                clearInterval(recordTimeInterval)
                clearInterval(playTimeInterval);
                this.recording = false, this.playing = false, this.hasRecord = false;
                this.playTime = 0, this.recordTime = 0;
                this.formatedRecordTime = "00:00:00", this.formatedRecordTime = "00:00:00";
            },
            clear() {
                this.end();
            },
            async checkPermission() {
                let status = permision.isIOS ? await permision.requestIOS('record') :
                    await permision.requestAndroid('android.permission.RECORD_AUDIO');

                if (status === null || status === 1) {
                    status = 1;
                } else if (status === 2) {
                    uni.showModal({
                        content: "系统麦克风已关闭",
                        confirmText: "确定",
                        showCancel: false,
                        success: function(res) {
                        }
                    })
                } else {
                    uni.showModal({
                        content: "需要麦克风权限",
                        confirmText: "设置",
                        success: function(res) {
                            if (res.confirm) {
                                permision.gotoAppSetting();
                            }
                        }
                    })
                }
                return status;
            },
			onUpload() {
				let fileName = new Date().getTime()
				let addFile = {
					name: fileName,
					filePath: music.src,
					ext: 'mp3',
					uploadState: '0'
				}
				sqliteUtil.insertMCpisFileAttachment(addFile).then(result=>{
					addFile.id = result
				})
				
				setTimeout(()=>{
					uni.navigateBack()
					if(this.source) {
						let data = {
							source: this.source,
							addFile: addFile
						}
						uni.$emit(this.emitkey, data)
					} else {
						uni.$emit(this.emitkey, addFile)
					}
				}, 500)
			}
        }
    }
</script>

<style lang="scss" scoped>
    image {
        width: 75px;
        height: 75px;
    }

    .page-body-time {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .time-big {
        font-size: 30px;
        margin: 10px;
		margin-top: 50px;
    }

    .time-small {
        font-size: 14px;
    }

    .page-body-buttons {
        margin-top: 30px;
        display: flex;
        justify-content: space-around;
    }

    .page-body-button {
        width: 120px;
        text-align: center;
    }

    .button-stop-record {
        width: 55px;
        height: 55px;
        border: 10px solid #fff;
        background-color: #f55c23;
        border-radius: 65px;
        margin: 0 auto;
    }
	
	.uploadBtn {
		padding: 8px;
		position: absolute;
		bottom: 0;
		width: calc(100% - 16px);
		
		button {
			background-color: #1E91E6;
			font-size: 16px;
		}
	}
</style>
